package longrise.phone.com.itssnew.activity;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.longrise.LEAP.Base.Encrypt.EncryptService;
import com.longrise.LEAP.Base.Objects.UserInfo;
import com.longrise.android.FrameworkManager;
import com.longrise.android.Global;
import com.longrise.android.util.StringUtils;

import butterknife.Bind;
import butterknife.OnClick;
import longrise.phone.com.itssnew.R;
import longrise.phone.com.itssnew.bean.Constant;
import longrise.phone.com.itssnew.bean.JZSQGloble;
import longrise.phone.com.itssnew.utils.CommonUtil;
import longrise.phone.com.itssnew.utils.SPUtil;
import longrise.phone.com.itssnew.widget.LoadDialog;


/**
 * Created by  on 17/6/19.
 */

public class LoginActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    @Bind(R.id.username)
    EditText username;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.login_maintenance)
    RadioButton loginMaintenance;
    @Bind(R.id.login_design)
    RadioButton loginDesign;
    @Bind(R.id.rg_login)
    RadioGroup rgLogin;
    @Bind(R.id.cb_login_rememberPass)
    CheckBox cbLoginRememberPass;
    @Bind(R.id.cb_login_auto)
    CheckBox cbLoginAuto;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.iv_setting)
    ImageView ivSetting;
    private LoadDialog dialog;
    private String userName;
    private String passWord;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initGloble();
    }

    @Override
    public int bindLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onStart() {
        super.onStart();
        AutoLogin();
        setClick();
    }

    private void setClick() {
        if (null != rgLogin) {
            rgLogin.setOnCheckedChangeListener(this);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.login_maintenance://运行维护
                SPUtil.setSharedIntData(this, Constant.SPOPERATIONSORDESIGN, 0);
                break;
            case R.id.login_design://咨询设计
                SPUtil.setSharedIntData(this, Constant.SPOPERATIONSORDESIGN, 1);
                break;
        }
    }


    private void AutoLogin() {
        Boolean ifAutoLogin = SPUtil.getSharedBooleanData(this, Constant.AUTOLOGIN);
        if(ifAutoLogin) {
            String autoUsername = SPUtil.getSharedStringData(this, Constant.USERNAME);
            String autoPassword = SPUtil.getSharedStringData(this, Constant.PASSWORD);
            username.setText(autoUsername);
            password.setText(autoPassword);
            login();
        }
    }

    private void initView() {
        int runType = SPUtil.getSharedIntData(this, Constant.SPOPERATIONSORDESIGN);
        if (runType == 0) loginMaintenance.setChecked(true);
        else loginDesign.setChecked(true);
        Boolean rememberPassword = SPUtil.getSharedBooleanData(this, Constant.REMEMBERPASSWORD);
        if(rememberPassword) {
            cbLoginRememberPass.setChecked(true);
            String usernameRemember = SPUtil.getSharedStringData(this, Constant.USERNAME);
            String passwordRemember = SPUtil.getSharedStringData(this, Constant.PASSWORD);
            username.setText(usernameRemember);
            password.setText(passwordRemember);
        }
        else {
            cbLoginRememberPass.setChecked(false);
            username.setText("");
            password.setText("");
        }
    }

    @OnClick({R.id.iv_setting, R.id.btn_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_setting:
                startActivity(SettingActivity.class);
                break;
            case R.id.btn_login:
                login();
                break;
        }
    }

    private void login(){
        userName = username.getText().toString().trim();
        passWord = password.getText().toString().trim();
        if(StringUtils.isEmpty(userName)){
            CommonUtil.showToast(this,"用户名不能为空");
            return;
        }
        if(StringUtils.isEmpty(passWord)){
            CommonUtil.showToast(this,"密码不能为空");
            return;
        }
        final  LoadDialog loadDialog = new LoadDialog(this);
        loadDialog.show();
        setRememberPassWordAndAutologin();
        passWord =EncryptService.getInstance().MD5Encrypt(passWord);
        String appid = Global.getInstance().getAppId();
        String apparea = Global.getInstance().getAppArea();
        String systemName = Global.getInstance().getSystemName();
        JZSQGloble.getInstance(this).call("app_systemloginWithSystemName", String.class, new JZSQGloble.OnCallFinishListener() {
            @Override
            public void onCallFinish(Object bean)
            {
                loadDialog.dismiss();
                if(bean==null){
                    CommonUtil.showToast(LoginActivity.this,"登录失败，请检查账号");
                    return;
                }
                switch (Integer.valueOf((String)bean)){
                    case 1:
                        getUserInfo();
                        break;
                    case -2:
                        CommonUtil.showToast(LoginActivity.this,"授权受限，拒绝登录");
                        break;
                    case -3:
                        CommonUtil.showToast(LoginActivity.this,"您的设备未注册，请与管理员联系");
                        break;
                    case -4:
                        CommonUtil.showToast(LoginActivity.this,"当前设备和登录用户不匹配，请与管理员联系");
                        break;
                    case -8:
                        CommonUtil.showToast(LoginActivity.this,"密码错误");
                        break;
                }
            }
        }, userName, passWord, systemName, appid, null, apparea);
    }


    private void setRememberPassWordAndAutologin() {
        if(cbLoginRememberPass.isChecked()) {
            SPUtil.setSharedBooleanData(this,Constant.REMEMBERPASSWORD,true);
            SPUtil.setSharedStringData(this,Constant.USERNAME,userName);
            SPUtil.setSharedStringData(this,Constant.PASSWORD,passWord);
        }
        else{
            SPUtil.setSharedBooleanData(this,Constant.REMEMBERPASSWORD,false);
            SPUtil.setSharedStringData(this,Constant.USERNAME,"");
            SPUtil.setSharedStringData(this,Constant.PASSWORD,"");
        }
        if(cbLoginAuto.isChecked()) SPUtil.setSharedBooleanData(this,Constant.AUTOLOGIN,true);
        else SPUtil.setSharedBooleanData(this,Constant.AUTOLOGIN,false);
    }


    private void getUserInfo(){
        JZSQGloble.getInstance(this).call("app_getUserInfo", UserInfo.class, new JZSQGloble.OnCallFinishListener() {
            @Override
            public void onCallFinish(Object bean)
            {
                if(bean == null)return;
                startActivity(CompanyActivity.class);
                finish();
                startHeartbeat();
                Global.getInstance().setUserInfo((UserInfo) bean);
            }
        });
    }

    private void initGloble() {
        DisplayMetrics dm = null;
        PackageManager pm = null;
        try {
            Global.getInstance().clean();
            Global.getInstance().setServerUrl(Constant.SERVERURL);
            Global.getInstance().setUpdateUrl(Constant.UPDATEURL);
            Global.getInstance().setLeapAppName(getString(R.string.leapAppName));
            String[] loginTypes = this.getResources().getStringArray(R.array.loginType);
            if (null != loginTypes && 5 == loginTypes.length) {
                Global.getInstance().setAppCode(loginTypes[0]);
                Global.getInstance().setAppId(loginTypes[1]);
                Global.getInstance().setAppValue(loginTypes[2]);
                Global.getInstance().setAppArea(loginTypes[3]);
                Global.getInstance().setSystemName(loginTypes[4]);
            }
            JZSQGloble.getInstance(this).setServerUrl(getString(R.string.ServerUrl));
            JZSQGloble.getInstance(this).setUpdateUrl(getString(R.string.UpdateUrl));
            JZSQGloble.getInstance(this).setLeapAppName(getString(R.string.leapAppName));
            JZSQGloble.getInstance(this).setRootDir(getString(R.string.appRootDir));
            FrameworkManager.getInstance().setAppdir(getString(R.string.appRootDir));
            pm = this.getPackageManager();
            if (null != pm) {
                PackageInfo packageInfo = pm.getPackageInfo(
                        this.getPackageName(), 0);
                if (null != packageInfo) {
                    Global.getInstance().setVersionCode(packageInfo.versionCode);
                    Global.getInstance().setVersionName(packageInfo.versionName);
                }
                packageInfo = null;
            }
            dm = new DisplayMetrics();
            if (null != dm) {
                this.getWindowManager().getDefaultDisplay().getMetrics(dm);
                FrameworkManager.getInstance().setDensity(dm.density);
                FrameworkManager.getInstance().setWinwidth(dm.widthPixels);
                FrameworkManager.getInstance().setWinheight(dm.heightPixels);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            dm = null;
            pm = null;
        }
    }
}
